<?php
/**
 * Created by PhpStorm
 * User: whh
 * Date: 2022/8/19
 * Time: 17:42
 */

namespace app\backstage\logic;


use app\backstage\model\ManagerRole;
use app\backstage\model\PowerNode;
use think\Db;

class PowerLogic
{
    public static $nodeModel;
    public static $paramsData;

    public function __construct($params = [])
    {
        self::$paramsData = $params;
        self::$nodeModel = app('powerNode');
    }

    /**
     * 树状表格用
     * @param $role
     * @return array
     * @Author: whh
     */
    public function treeNodes(ManagerRole $role = null)
    {
        $list = self::$nodeModel->order('order desc,id asc')->select();
        $list = $list->toArray();
        if ($role) {
            $roleNodes = $role->nodes->toArray();
            $roleNodeIds = array_column($roleNodes, 'id');
            foreach ($list as $k => $v) {
                if (in_array($v['id'], $roleNodeIds)) {
                    $list[$k]['LAY_CHECKED'] = true;
                } else {
                    $list[$k]['LAY_CHECKED'] = false;
                }
            }
        }
        return self::packageArray($list, 'id', 'parent_node_id', 'treeList', 0);
    }

    /**
     * 树状表菜单
     * @param ManagerRole|null $role
     * @return array
     * @Author: whh
     */
    public function treeMenu(ManagerRole $role = null)
    {
        $roleNodes = $role->nodes->toArray();
        $roleNodeIds = array_column($roleNodes, 'id');
        $where[] = ['type', '=', 2];
        $where[] = ['status', '=', 1];
        $where[] = ['id', 'in', $roleNodeIds];
        $list = self::$nodeModel->where($where)->order('order desc,id asc')->select();
        $list = $list->toArray();
        return self::packageArray($list, 'id', 'parent_node_id', 'treeList', 0);
    }


    /**
     * 菜单格式化
     * @param $menus
     * @param int $layers
     * @param string $home_page
     * @return string
     * @Author: whh
     */
    public function menuFormat($menus, $layers = 0, $home_page = '')
    {
        $html = '';
        if ($layers === 0) {
            foreach ($menus as $k => $v) {
                /**
                 * 设置首页选中展开
                 */
                $thisClass = '';
                if ($home_page != '' && isset($v['treeList'])) {
                    $sonNodePathArr = $this->array_get_by_key($v['treeList'], 'node_path');
                    if (in_array($home_page, $sonNodePathArr)) {
                        $thisClass = 'layui-nav-itemed';
                    }
                }elseif ($home_page != '' && !isset($v['treeList']) && '"'.$v['node_path'].'"' == $home_page){
                     $thisClass = 'layui-this';
                }

                $html .= '<li data-name="' . $v['permission_id'] . '" class="layui-nav-item ' . $thisClass . '">';
                if (isset($v['treeList'])) {
                    $html .= '<a href="javascript:;" lay-tips="' . $v['title'] . '"><i class="layui-icon"><span class="iconfont ' . $v['icon'] . '"></span></i><cite>' . $v['title'] . '</cite></a>';
                    $html .= $this->menuFormat($v['treeList'], $layers + 1, $home_page);
                } else {
                    $html .= '<a href="javascript:;" lay-href="/' . $v['node_path'] . '"  lay-tips="' . $v['title'] . '"><i class="layui-icon"><span class="iconfont ' . $v['icon'] . '"></span></i><cite>' . $v['title'] . '</cite></a>';
                }
                $html .= '</li>';
            }
        } else {
            $html .= '<dl class="layui-nav-child">';
            foreach ($menus as $k => $v) {

                /**
                 * 设置首页选中展开
                 */
                $thisClass = '';
                if ($home_page != '' && isset($v['treeList'])) {
                    $sonNodePathArr = $this->array_get_by_key($v['treeList'], 'node_path');
                    if (in_array($home_page, $sonNodePathArr)) {
                        $thisClass = 'layui-nav-itemed';
                    }
                }elseif ($home_page != '' && !isset($v['treeList']) && '"'.$v['node_path'].'"' == $home_page){
                    $thisClass = 'layui-this';
                }

                if (isset($v['treeList'])) {
                    $html .= '<dd class="'.$thisClass.'"><a href="javascript:;">' . $v['title'] . '</a>';
                    $html .= $this->menuFormat($v['treeList'], $layers + 1, $home_page);
                    $html .= '</dd>';
                } else {
                    $html .= '<dd class="'.$thisClass.'" data-name="' . $v['permission_id'] . '"><a lay-href="/' . $v['node_path'] . '">' . $v['title'] . '</a></dd>';
                }
            }
            $html .= '</dl>';
        }
        return $html;
    }


    function array_get_by_key(array $array, $string)
    {
        if (!trim($string)) return false;
        preg_match_all("/\"$string\";\w{1}:(?:\d+:|)(.*?);/", serialize($array), $res);
        return $res[1];
    }


    /**
     * 将数据变为树状结构
     * @param $list
     * @param string $pk
     * @param string $pid
     * @param string $child
     * @param int $root
     * @return array
     * @Author: whh
     */
    public static function packageArray($list, $pk = 'id', $pid = 'parent_node_id', $child = 'list', $root = 0)
    {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] =& $list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = $data[$pid];
                if ($root === $parentId) {
                    $tree[] =& $list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent =& $refer[$parentId];
                        $parent[$child][] =& $list[$key];
                    }
                }

            }
        }
        return $tree;
    }


    /**
     * 添加节点
     * @param $parent_node_id
     * @return int|string
     * @Author: whh
     */
    public function addNode($parent_node_id)
    {
        return self::$nodeModel->insertGetId([
            'parent_node_id' => $parent_node_id
        ]);
    }


    /**
     * @param $role_id 角色id
     * @param $id 节点id
     * @param $checked 是否选中
     * @return \think\response\Json
     * @Author: whh
     */
    public function authNode($role_id, $id, $checked)
    {
        $role = ManagerRole::get($role_id);
        if (!$role) {
            return errJson('角色异常');
        }
        if ($checked) {
            $node = self::$nodeModel::get($id);
            if (!$node) {
                return errJson('节点不存在');
            }
            $role->nodes()->save($id);
        } else {
            $role->nodes()->detach($id);
        }
        return sucJson();
    }


    /**
     * 修改节点
     * @param $params
     * @Author: whh
     */
    public function upNode($params)
    {
        self::$nodeModel->where("id", $params['id'])->setField($params['field'], trim($params['value']));
    }


    /**
     * 删除节点
     * @param $id
     * @return \think\response\Json
     * @throws \Exception
     * @Author: whh
     */
    public function delNode($id)
    {
        $flag = self::$nodeModel->where('parent_node_id', $id)->find();
        if ($flag) {
            return errJson('存在下属节点，删除失败');
        }
        $node = self::$nodeModel->get($id);
        $node->roles()->detach();
        $node->delete();
        return sucJson();
    }
}